<?php

namespace App\Http\Middleware;

use Closure;
use App\Exceptions\InvalidRequestException;

class OAuthScopeMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @param  \String $scopes
     * @return mixed
     */
    public function handle($request, Closure $next, $scopes)
    {
        $requestScopes = $request->header("X-Authenticated-Scope");
        $requestScopes = explode(' ', $requestScopes);

        $scopes = preg_split('/\s+/', trim($scopes));

        if (empty(array_intersect($requestScopes, $scopes))) {
            throw new InvalidRequestException();
        }

        return $next($request);
    }
}
